package com.example.mystore.service.impl;

import com.example.mystore.mapper.ProductMapper;
import com.example.mystore.model.Product;
import com.example.mystore.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;
import java.util.Date;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Value("upload")
    private String uploadDir;

    @Override
    public void addProduct(Product product) {
        Product originalProduct=productMapper.selectProductById(product.getProductId());
        product.setCreated(new Date());
        product.setUpdated(originalProduct.getUpdated());
        productMapper.insertProduct(product);
    }


    @Override
    public void updateProduct(Product product) {
        Product originalProduct=productMapper.selectProductById(product.getProductId());
        product.setIsHot(originalProduct.getIsHot());
        product.setStatus(originalProduct.getStatus());
       product.setCreated(originalProduct.getCreated());
        product.setUpdated(new Date());
        productMapper.updateProduct(product);
    }

    @Override
    public Product getProductById(int id) {
        return productMapper.selectProductById(id);
    }
    @Override
    public String saveImage(MultipartFile image) throws IOException {
        String fileName = UUID.randomUUID() + "_" + image.getOriginalFilename();
        Path filePath = Paths.get(uploadDir, fileName);
        Files.createDirectories(filePath.getParent());
        Files.write(filePath, image.getBytes());
        return "/upload/" + fileName;
    }

    @Override
    public List<Product> getAllProducts() {
        return productMapper.selectAllProducts();
    }

    @Override
    public void toggleProductStatus(int id) {
        Product product = productMapper.selectProductById(id);
        if (product != null) {
            switch (product.getStatus()) {
                case 1:
                    product.setStatus(2); // 待售 -> 上架
                    break;
                case 2:
                    product.setStatus(3); // 上架 -> 下架
                    break;
                case 3:
                    product.setStatus(1); // 下架 -> 待售
                    break;
            }
            productMapper.updateProduct(product);
        }
    }

    @Override
    public void toggleHotStatus(int id) {
        Product product = productMapper.selectProductById(id);
        if (product != null) {
            product.setIsHot(product.getIsHot() == 1 ? 2 : 1);
            productMapper.updateProduct(product);
        }
    }



}
